import 'dart:io';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yuan_hang_app/base/custom_appbar.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/menu_helper.dart';
import 'package:yuan_hang_app/utils/permission_util.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/widget/custom_dot_builder.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List bannerList = [
    "images/Y6.jpg",
    "images/Y7.jpg",
    "images/H8.jpg",
    "images/H9.jpg",
    // "https://files.yuanhangqiche.com/source/guanyuyuanhang/3840-1920.jpg",
    // "https://files.yuanhangqiche.com/source/upload/b512e9a7ca1d4092bdb7b60d5c149d6f.jpg",
    // "https://files.yuanhangqiche.com/source/upload/71948e93ec68475eab801d0d930f2f08.jpg",
    // "https://files.yuanhangqiche.com/source/upload/9b01b18078e348a6843c4b3613dc915b.jpg",
    // "https://files.yuanhangqiche.com/source/upload/d0bb9bf3439d442e9b0c454bc6e1d74b.jpg",
  ]; //头部 banner
  ScrollController scrollController = ScrollController(); //监听列表是否滑到最底部
  int loadStatus = 3; //上拉加载 0不在加载中，1加载中，2无更多加载数据,3整体无数据
  static List menuList = [
    // {"MENU_URL": "menu_leads_loop", "MENU_NAME": "线索池"},
    // {"MENU_URL": "menu_leads_assign", "MENU_NAME": "线索分配"},
    // {"MENU_URL": "menu_leads_register", "MENU_NAME": "线索登记"},
    // {"MENU_URL": "menu_leads_follow_up", "MENU_NAME": "线索跟进"},
    // {"MENU_URL": "menu_leads_adult", "MENU_NAME": "战败审核"},
    // {"MENU_URL": "menu_leads_defeat_loop", "MENU_NAME": "战败线索池"},
    // {"MENU_URL": "menu_book_manager", "MENU_NAME": "预约管理"},
    // {"MENU_URL": "menu_book_drive", "MENU_NAME": "试驾管理"},
    // {"MENU_URL": "menu_driver_back", "MENU_NAME": "试驾回访"},
    // {"MENU_URL": "menu_activity", "MENU_NAME": "市场活动"},
    // {"MENU_URL": "menu_order", "MENU_NAME": "代客下单"},
    // {"MENU_URL": "menu_finance_compute", "MENU_NAME": "金融计算器"},
    // {"MENU_URL": "menu_vehicle_stock", "MENU_NAME": "车辆库存"}
  ];
  List countList = [
    {"count": 100, "title": "当前线索数"},
    {"count": 64, "title": "新增线索数"},
    {"count": 58, "title": "当前客户数"},
    {"count": 76, "title": "新增客户数"},
    {"count": 32, "title": "跟进客户数"},
    {"count": 46, "title": "新增跟进数"},
    {"count": 39, "title": "成交客户数"},
    {"count": 49, "title": "新增成交数"},
  ];


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    scrollController.addListener(() {
      if (loadStatus == 0 &&
          scrollController.position.pixels >=
              scrollController.position.maxScrollExtent) {
        //判断滑到表格底部
        if (!mounted) return;
        setState(() {
          loadStatus = 1;
          //  getHomeConsultList(true);
        });
      }
      double alpha = scrollController.offset / 180.px;
      if (mounted && alpha >= -0.5 && alpha <= 1.5) {
        if (alpha < 0) {
          alpha = 0;
        } else if (alpha > 1) {
          alpha = 1;
        }
        //       navigatorKey.currentState.onChangeAlpha(1 - alpha);
      }
    });
    CommonReqUtils.getSalesmanList();
    if (WConstant.modelList.isEmpty) {
      CommonReqUtils.saveModelList();
    }
   getHomeMenu();
  }

  void getHomeMenu() {
    Toast.showLoading();
    HttpUtils()
        .get("${Api.getHomeMenuList}?empId=${WConstant().userInfo.empId}")
        .then((data) {
      if (data.resultCode == 200) {
        menuList = data.data ?? [];
        setState(() {});
      } else if (data.resultCode == 500) {
        Toast.toast(data.errMsg);
      }
      if (data.resultCode != 401) {
        Toast.dismissLoading();
      }
    }).catchError((e) {
      Toast.dismissLoading();
    });
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh,
      child: SingleChildScrollView(
        child: SizedBox(
          height: SizeUtils.screenH(),
          width: SizeUtils.screenW(),
          child: Column(
            children: [
              CustomAppBar(
                leftWidget: const SizedBox(),
                contentTitle: "首页",
              ),
              Expanded(
                  child: ListView(
                padding: EdgeInsets.zero,
                controller: scrollController,
                shrinkWrap: true,
                children: [
                  Stack(
                    children: [
                      // SizedBox(
                      //   height: 275.px,
                      //   width: SizeUtils.screenW(),
                      // ),
                      bannerItemView(),
                      // Positioned(
                      //   top: 120.px,
                      //   left: 0,
                      //   child: countView(),
                      // ),
                    ],
                  ),
                  mainItemView(),
                ],
              ))
            ],
          ),
        ),
      ),
    );
  }

  Future<Null> _refresh() async {
    getHomeMenu();
  }

  Widget bannerItemView() {
    return Container(
        height: 160.px,

        ///    margin: EdgeInsets.symmetric(horizontal: 20.px,),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.px)),
        child: bannerList.isEmpty
            ? Image.asset(
                "images/banner.png",
                fit: BoxFit.fill,
              )
            :

        Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {},
                    child: Image.asset(bannerList[index],fit: BoxFit.cover,)//Image.network(bannerList[index],fit: BoxFit.cover,)

                  );
                },
                itemCount: bannerList.length,
                autoplay: true,
              //  viewportFraction: 1.0,
                pagination: bannerList.length > 1
                    ? SwiperPagination(
                        margin: EdgeInsets.only(top: 3.px, bottom: 20.px),
                        builder: CustomDotBuilder(
                            color: const Color(0x55FFFFFF),
                            activeColor: const Color(0xBBffffff),
                            size: 6.px,
                            activeSize: 6.px,
                            haveBorder: false))
                    : const SwiperPagination()),
        );
  }

  Widget mainItemView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.only(left: 20.px, right: 20.px, top: 10.px),
          child: WText(
            "工作台",
            style: TextStyle(
                color: WColors.mainTextColor,
                fontSize: 16.px,
                fontWeight: FontWeight.bold),
          ),
        ),
        GridView.builder(
          padding: EdgeInsets.all(15.px),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              mainAxisSpacing: 10.px,
              crossAxisCount: 4,
              crossAxisSpacing: 10.px,
              childAspectRatio: 1),
          itemBuilder: gridItem,
          itemCount: menuList.length,
        )
      ],
    );
  }

  Widget gridItem(context, index) {
    Map item = menuList[index];
    return GestureDetector(
      onTap: () {
        MenuHelper.menuRoute(item["MENU_NAME"], context);
      },
      child: Container(
          alignment: Alignment.center,
          color: WColors.CF8F9FA,
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  "images/${item['MENU_URL']}.png",
                  width: 40.px,
                ),
                SizedBox(
                  height: 5.px,
                ),
                WText(item["MENU_NAME"],
                    style: TextStyle(
                      fontSize: 14.px,
                      color: WColors.mainTextColor,
                    )),
              ])),
    );
  }

  Widget countView() {
    return Container(
//      height: 300.px,
      width: SizeUtils.screenW() - 30.px,
      margin: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
            color: WColors.CDFEFFB,
            offset: const Offset(0, 1),
            blurRadius: 3.px)
      ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
      child: GridView.builder(
        padding: EdgeInsets.all(10.px),
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            mainAxisSpacing: 5.px,
            crossAxisCount: 4,
            crossAxisSpacing: 5.px,
            childAspectRatio: 1.3),
        itemBuilder: countItem,
        itemCount: countList.length,
      ),
    );
  }

  Widget countItem(context, index) {
    Map item = countList[index];
    return GestureDetector(
      onTap: () {
        //  MenuHelper.menuRoute(item["title"], context);
      },
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            WText(
              item["count"].toString(),
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.px,
                  color: WColors.mainTextColor),
            ),
            SizedBox(
              height: 5.px,
            ),
            WText(item["title"],
                style: TextStyle(
                  fontSize: 12.px,
                  color: WColors.mainTextColor,
                )),
          ]),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
